<template>
  <div class="app-container">
    <div>
      <el-row class="admin-top">
        <template v-if="limits.length >=1 && limits.filter(it => it.FName === '查看').length">
          <el-input v-model="keyword" clearable style="width: 195px;" placeholder="关键字搜索" @keyup.native.enter="searchUser" @change="searchUser"/>
          <el-select v-model="fdeptname" clearable placeholder="请选择部门" @change="searchUser">
            <el-option
              v-for="item in bmList"
              :key="item.finterid"
              :label="item.fname"
              :value="item.fname"/>
          </el-select>
          <el-button type="primary" icon="el-icon-search" @click="searchUser">搜索</el-button>
        </template>
        <el-button v-if="limits.length >=1 && limits.filter(it => it.FName === '新增').length" type="success" icon="el-icon-plus" @click="addUser">添加</el-button>
        <el-button v-if="limits.length >=1 && limits.filter(it => it.FName === '修改').length" type="success" icon="el-icon-edit" @click="editUser">编辑</el-button>
        <el-button v-if="limits.length >=1 && limits.filter(it => it.FName === '删除').length" type="success" icon="el-icon-delete" @click="delUser">删除</el-button>
      </el-row>
    </div>
    <br>
    <el-table
      v-loading="listLoading"
      v-if="limits.length >=1 && limits.filter(it => it.FName === '查看').length"
      :data="list"
      :height="tableHeight"
      element-loading-text="正在加载"
      border
      fit
      highlight-current-row
      @current-change="salaryCurrentChange">
      <el-table-column label="账号" align="center">
        <template slot-scope="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
      <el-table-column label="用户名" align="center">
        <template slot-scope="scope">
          {{ scope.row.customername }}
        </template>
      </el-table-column>
      <el-table-column label="公司名称" align="center">
        <template slot-scope="scope">
          {{ scope.row.company }}
        </template>
      </el-table-column>

      <el-table-column label="部门" align="center">
        <template slot-scope="scope">
          {{ scope.row.fdeptname }}
        </template>
      </el-table-column>

      <el-table-column label="手机号码" align="center">
        <template slot-scope="scope">
          {{ scope.row.fphone }}
        </template>
      </el-table-column>

      <el-table-column label="上班时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.starttime }}
        </template>
      </el-table-column>
      <el-table-column label="下班时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.endtime }}
        </template>
      </el-table-column>
      <el-table-column label="是否启动上下班时间" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.qdtimeStatus === 1">{{ '是' }}</span>
          <span v-else>{{ '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.create_time }}
        </template>
      </el-table-column>
      <el-table-column label="登录状态是否禁用" align="center">
        <template slot-scope="scope">
          <span v-if="Number(scope.row.status) === 1">{{ '否' }}</span>
          <span v-else>{{ '是' }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column
        fixed="right"
        label="操作"
        width="100">
        <template slot-scope="scope">
          <el-button v-if="Number(scope.row.status) === 1" type="text" size="small" @click="handleClick(scope.row)">
            启用
          </el-button>
          <el-button v-else type="text" size="small" @click="handleClick(scope.row)">
            禁用
          </el-button>
        </template>
      </el-table-column> -->

    </el-table>
    <el-pagination
      v-if="limits.length >=1 && limits.filter(it => it.FName === '查看').length"
      :total="total"
      :page-sizes="pagesizes"
      :page-size="pagesize"
      :current-page.sync="currentPage"
      class="jy-pagination"
      style="text-align: center; margin-top: 20px;"
      background
      layout="sizes, prev, pager, next, total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"/>

    <el-dialog v-el-drag-dialog :visible.sync="addUserModal" title="添加／编辑" width="50%" >
      <el-form v-loading="loadingForm" ref="form" :rules="rules" :model="form" label-width="140px">
        <el-form-item label="账号" prop="username">
          <el-col :span="9">
            <el-input :disabled="!!form.id" v-model="form.username"/>
          </el-col>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-col :span="9">
            <el-input :type="pwdType" v-model="form.password" />
            <span class="show-pwd" @click="showPwd">
              <svg-icon icon-class="eye" />
            </span>
          </el-col>
        </el-form-item>
        <el-form-item label="用户名" prop="customername">
          <el-col :span="9">
            <el-input v-model="form.customername"/>
          </el-col>
        </el-form-item>
        <el-form-item label="公司名称" prop="company">
          <el-col :span="9">
            <el-input v-model="form.company"/>
          </el-col>
        </el-form-item>

        <el-form-item label="部门" prop="fdeptname">
          <el-select v-model="form.fdeptname" clearable filterable placeholder="请选择部门" >
            <el-option
              v-for="item in bmList"
              :key="item.finterid"
              :label="item.fname"
              :value="item.fname"/>
          </el-select>
        </el-form-item>

        <el-form-item label="手机号" prop="fphone" >
          <el-col :span="9">
            <el-input v-model="form.fphone"/>
          </el-col>
        </el-form-item>

        <el-form-item label="上班时间" prop="starttime">
          <el-time-select
            v-model="form.starttime"
            :picker-options="{
              start: '07:00',
              step: '00:15',
              end: '18:30'
            }"
            placeholder="上班时间"
            @change="startTime"/>
        </el-form-item>
        <el-form-item label="下班时间" prop="endtime">
          <el-time-select
            v-model="form.endtime"
            :picker-options="{
              start: '07:00',
              step: '00:15',
              end: '18:30'
            }"
            placeholder="下班时间"
            @change="endTime"/>
        </el-form-item>
        <el-form-item label="是否启动上下班时间" prop="qdtimeStatus">
          <el-radio-group v-model="form.qdtimeStatus">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="登录状态是否禁用" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">否</el-radio>
            <el-radio :label="0">是</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button :loading="loadingForm" type="primary" @click="confirm('form')" >确认</el-button>
          <el-button @click="addUserModal=false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { admin, adminAdd, adminEdit, adminDel } from '../../api/account'
import { common } from '../../mixins/common'
import { pagination } from '../../mixins/pagination'
import { bumen } from '../../mixins/bumen'
export default {
  mixins: [common, pagination, bumen],
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (!(/^[0-9a-zA-Z]+$/.test(value))) {
          callback(new Error('密码由数字字母组成'))
        } else {
          callback()
        }
      }
    }
    return {
      keyword: '',
      listLoading: false,
      list: [],

      // 弹窗
      curData: {},
      pwdType: 'password',
      form: {
        username: '', // 账号
        customername: '', // 用户名
        password: '', // 密码
        company: '',
        create_time: '',
        starttime: '',
        endtime: '',
        qdtimeStatus: 0,
        status: 0,
        fdeptname: '',
        fphone: ''

      },
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        fphone: [
          { required: true, message: '请输入手机号', trigger: 'blur' }
        ],
        fdeptname: [
          { required: true, message: '请选择一个部门', trigger: 'change' }
        ],
        password: [
          { required: true, validator: validatePass, trigger: 'blur' }
        ]
      },
      addUserModal: false,
      loadingForm: false,
      loginname: '',
      // 用户菜单
      menusList: [],
      limits: [],
      userKey: '',

      pagesizes: [20, 50, 100, 300, 500]
    }
  },
  async mounted() {
    // this.menusList = this.globalDb.menusList
    this.userKey = this.$route.meta.FRepKey

    this.loginname = decodeURIComponent(this.globalDb.fname)
    await this.getAdmin()
  },
  methods: {
    handleClick(val) {
      console.log(val, ' val handleClick')
    },
    startTime(val) {

    },
    endTime(val) {

    },
    showPwd() {
      if (this.pwdType === 'password') {
        this.pwdType = ''
      } else {
        this.pwdType = 'password'
      }
    },
    searchUser() {
      this.getAdmin()
    },
    async getAdmin() {
      try {
        this.listLoading = true
        const res = await admin({
          db: this.globalDb.db,
          opername: this.loginname,
          keyword: this.keyword,
          fdeptname: this.fdeptname,
          username: this.loginname,
          limit: this.pagesize,
          page: this.currentPage
        })

        // 菜单列表（权限）
        const menuRes = JSON.parse(localStorage.getItem('setMenuData'))
        this.menusList = menuRes

        if (menuRes.length >= 1) {
          menuRes.map(it => {
            it.children.map(item => {
              if (item.fobjectid === this.userKey) {
                this.$set(this, 'limits', item.child)
              }
            })
          })
        }

        this.list = res.result
        console.log(res.result, ' res.result')
        this.total = res.total
        this.listLoading = false
      } catch (error) {
        this.listLoading = false
        // console.log(error)
      }
    },
    salaryCurrentChange(val) {
      this.curData = val
    },
    async addUser() {
      this.pwdType = 'password'
      this.form = {}
      const data = {
        customername: '',
        username: '',
        password: '',
        company: '',
        create_time: '',
        starttime: '07:00',
        endtime: '18:30',
        qdtimeStatus: 0,
        status: 1,
        fdeptname: '',
        fphone: ''

      }
      for (const i in data) {
        this.$set(this.form, i, data[i])
      }
      setTimeout(() => {
        this.$refs['form'].clearValidate()
      })

      this.addUserModal = true
    },
    async editUser() {
      this.pwdType = 'password'
      this.form = {
        customername: '',
        username: '',
        password: '',
        company: '',
        create_time: '',
        starttime: '07:00',
        endtime: '18:30',
        qdtimeStatus: 0,
        status: 0,
        fdeptname: '',
        fphone: ''

      }
      const data = this.curData
      if (!data || !data.id) {
        this.$message({
          message: '请选中要编辑的一行',
          type: 'warning'
        })
        return
      }
      this.addUserModal = true
      for (const i in this.form) {
        this.$set(this.form, i, data[i])
      }
      this.form.id = data.id
      setTimeout(() => {
        this.$refs['form'].clearValidate()
      })
    },
    async confirm() {
      this.$refs['form'].validate(async(valid) => {
        if (valid) {
          this.loadingForm = true
          try {
            this.form.db = this.globalDb.db
            this.form.opername = this.loginname
            let res = ''
            if (this.form.id) {
              res = await adminEdit(this.form)
            } else {
              res = await adminAdd(this.form)
            }
            if (res.code === 200) {
              this.loadingForm = false
              this.addUserModal = false
              this.$message({
                message: res.message,
                type: 'success'
              })
              this.getAdmin()
            } else {
              this.loadingForm = false
              this.$message({
                message: res.message,
                type: 'error'
              })
            }
          } catch (error) {
            this.loadingForm = false
          }
        } else {
          return false
        }
      })
    },
    async delUser() {
      const data = this.curData

      if (data === null || !data.id) {
        this.$message({
          message: '请选中要删除的一行',
          type: 'warning'
        })
        return
      }

      if (data.username === 'manager') {
        this.$message({
          message: '超级用户不能删除',
          type: 'warning'
        })
        return
      }

      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'btn-custom-cancel',
        type: 'warning'
      }).then(async() => {
        const id = data.id
        const res = await adminDel({
          db: this.globalDb.db,
          opername: this.loginname,
          data,
          id
        })
        if (res.Error === 0) {
          this.$message({
            message: res.Message,
            type: 'success'
          })
          this.getAdmin()
          return
        }
        this.$message({
          message: res.Message,
          type: 'error'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSizeChange(val) {
      this.currentPage = 1
      this.pagesize = val
      this.getAdmin()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getAdmin()
    }
  }
}
</script>
<style lang="scss" scoped>
  $dark_gray:#889aa4;
  .show-pwd {
    position: absolute;
   // right: 10px;
    //top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
</style>
